package hk.com.carfield.persistance;

import hk.com.carfield.content.Image;
import hk.com.carfield.core.Context;
import hk.com.carfield.util.UrlUtil;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;

@Entity
public class GenericEntity {
	public static byte[] getByte(final Context ctx, final File location)
			throws UnsupportedEncodingException, IOException {
		// TODO should not depend on Image type only
		final String key = UrlUtil.getUrl(ctx.config, location);
		GenericEntity entity = ctx.persistMan.genericDA.pIdx.get(key);
		if (entity == null) {
			final byte[] thumbnail = Image.scaleImage(ctx.config, location);
			entity = new GenericEntity(key, thumbnail);
			ctx.persistMan.genericDA.pIdx.put(entity);
		}
		return entity.data == null ? new byte[0] : entity.data;
	}

	private final byte[] data;

	@SuppressWarnings("unused")
	@PrimaryKey
	private final String path;

	/**
	 * @deprecated This is just an requirement for DBD internal, we should never
	 *             use this API
	 */
	@Deprecated
	public GenericEntity() {
		path = null;
		data = null;
	}

	public GenericEntity(final String path, final byte[] data) {
		this.path = path;
		this.data = data;
	}
}
